include("../../static/js/config.js");
include("../../static/js/common.js");

var tree;
var data = [];

$(function () {

    layui.use(['tree', 'layer'], function () {
        var $ = layui.jquery;
            tree = layui.tree;

        var layer = layui.layer;

        var roleId = getParam('roleId');
        asyncRequest("/admin/resource/treeList", {roleId: roleId}, function (res) {
            if (res.code === 200){
                data = res.data;
            }
        });

        tree.render({
            elem: '#treeDiv'
            ,data: data
            ,showCheckbox: true  
            ,id: 'resourceTree'
            ,isJump: true,
            onlyIconControl: true
        });
    
        $('#submitBtn').click(function () {

            var nodes = tree.getChecked('resourceTree');
            if (nodes.length == 0){
                layer.msg('至少选中一个');
                return;
            }

            var ids = [];
            getResourceId(ids, nodes);
            request("/admin/role/bindResources", {id:roleId, resourceIds: ids}, function (res) {
                if (res.code === 200){
                    if (window.parent){
                        window.parent.layer.closeAll();
                        window.parent.layer.msg(res.msg, {icon: 1});
                    } else {
                       layer.msg(res.msg, {icon: 5});
                    }
                }
            })
        })
   
    });
});


function getResourceId(ids, nodes) {
    if (nodes){
        for (var i = 0; i < nodes.length; i++){
            ids.push(nodes[i].id);
            getResourceId(ids, nodes[i].children);
        }
    }
}
